package org.jmh.gift.listener;

import org.jmh.gift.constants.GiftConstants;
import org.jmh.gift.doc.GiftDoc;
import org.jmh.gift.repository.GiftDocRepository;
import com.alibaba.fastjson.JSONArray;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 礼物上架的消息监听器:监听指定队列,获取到队列中的消息,存入es
 */
@Component
@RocketMQMessageListener(topic = GiftConstants.GIFT_ONSALE_TX_TOPIC,
        consumerGroup = GiftConstants.GIFT_ONSALE_TX_CONSUMER_GROUP)
public class OnsaleMessageListener implements RocketMQListener<MessageExt> {

    @Autowired
    private GiftDocRepository giftDocRepository;

    /**
     * 当有消息到达消息队列以后,就会被这个方法所执行
     * @param message
     */
    @Override
    public void onMessage(MessageExt message) {
        // 1 获取消息
        byte[] body = message.getBody();
        // s是json数组格式的字符串
        String s = new String(body);
        // 将一个json格式的字符串转成对象,只需要保证字符串中的字段和转换后的对象中的字段名保持一致
        List<GiftDoc> giftDocs = JSONArray.parseArray(s, GiftDoc.class);
        // 2 将消息存入es
        giftDocRepository.saveAll(giftDocs);
    }
}
